import 'package:flutter/material.dart';
import 'package:flutter_rtk/common/constants.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class RefreshListWidget extends StatefulWidget {
  final List dataList;
  final Function itemBuilder;
  final Function separatorBuilder;
  final Function? onRefresh;
  final Function? onLoading;

  const RefreshListWidget({super.key, required this.dataList, required this.itemBuilder, required this.separatorBuilder, required this.onRefresh, required this.onLoading});

  @override
  State<RefreshListWidget> createState() => _RefreshListWidgetState();
}

class _RefreshListWidgetState extends State<RefreshListWidget> {
  late RefreshController _refreshController;

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      enablePullDown: widget.onRefresh != null,
      enablePullUp: widget.onLoading != null,
      header: WaterDropHeader(complete: Text("刷新成功", style: TextStyle(fontSize: 28.sp, color: AppConstants.brandColor, fontWeight: FontWeight.normal)), waterDropColor: AppConstants.brandColor),
      footer: const ClassicFooter(failedText: "加载失败,稍后再试", loadingText: "加载中...", noDataText: "暂无更多数据", idleText: "上拉加载更多数据", canLoadingText: "释放加载更多数据"),
      onRefresh: () async {
        // print("onRefresh");
        try {
          await widget.onRefresh!();
          _refreshController.refreshCompleted();
        } catch (e) {
          _refreshController.refreshFailed();
        }
      },
      onLoading: () async {
        try {
          List dataList = await widget.onLoading!();
          if (dataList.isEmpty) {
            _refreshController.loadNoData();
            return;
          }
          _refreshController.loadComplete();
        } catch (e) {
          // print(e);
          _refreshController.loadFailed();
        }
      },
      child: ListView.separated(
        itemBuilder: (context, idx) {
          return widget.itemBuilder(widget.dataList[idx]);
        },
        itemCount: widget.dataList.length,
        separatorBuilder: (context, idx) => widget.separatorBuilder(idx),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController();
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }
}
